package com.ash.datasocket.simple;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketAddress;

public class DataSocketServer {

    public static void main(String[] args) throws Exception {

        byte[] buf = new byte[1024];
        DatagramPacket recPacket = new DatagramPacket(buf, buf.length);

        DatagramSocket ds = new DatagramSocket(71);

        // 接收 请求
        ds.receive(recPacket);

        String recMsg = new String(buf, 0, recPacket.getLength());
        System.out.println("对方发送的消息：" + recMsg);

        InetAddress sendIP = recPacket.getAddress();
        int sendPort = recPacket.getPort();
        System.out.println("对方的IP地址是：" + sendIP.getHostAddress());
        System.out.println("对方的端口号是：" + sendPort);

        String resMsg = "接收方说：我收到了！";
        byte[] resBuf = resMsg.getBytes();

        // 返回响应
        SocketAddress clientSocketAddress = recPacket.getSocketAddress();

        DatagramPacket resPacket = new DatagramPacket(resBuf, resBuf.length, clientSocketAddress);

        ds.send(resPacket);

        ds.close();

    }

}
